package com.chx.shiro.realms;

import com.chx.dao.UserDAO;
import com.chx.entity.Perms;
import com.chx.entity.Role;
import com.chx.entity.User;
import com.chx.shiro.salt.MyByteSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    UserDAO userDAO;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        User user = userDAO.queryRolesByUserName(primaryPrincipal);
        if(user!=null){
            if(!CollectionUtils.isEmpty(user.getRoles())){
                SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
                user.getRoles().forEach(role->{
                    simpleAuthorizationInfo.addRole(role.getName());
                    List<Perms> perms = userDAO.queryPermsByRoleId(role.getId());
                    perms.forEach(perms1 -> {
                        simpleAuthorizationInfo.addStringPermission(perms1.getName());
                    });
                });
                return simpleAuthorizationInfo;
            }
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        User user = userDAO.queryUserByUserName(principal);
        if(user!=null){
            return new SimpleAuthenticationInfo(principal, user.getPassword(),new MyByteSource(user.getSalt()),this.getName());
        }
        return null;
    }
}
